package com.solution.admin.product.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.solution.admin.product.entity.ProductCategoryEntity;
import com.solution.admin.product.service.ProductCategoryService;
import com.solution.common.constants.PublicStatus.IS_DELETE;
import com.solution.common.constants.PublicStatus.STATUS;
import com.solution.common.controller.BaseController;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;

/**
 * 商品类别信息web控制层
 * 
 * @author xu_cc
 * @date 2017-08-31 23:52:27
 */
@RequestMapping("/productCategory")
@Controller(value = "/productCategory")
public class ProductCategoryController extends BaseController {

	private Logger logger = LoggerFactory
			.getLogger(ProductCategoryController.class);

	@Autowired
	private ProductCategoryService productCategoryService;

	/**
	 * 商品分类树形图
	 * 
	 * @param categoryCode void
	 * @author xu_cc
	 * @throws Exception exception
	 * @Date 创建时间：2017年9月17日 下午7:40:16
	 */
	@RequestMapping("/categoryTree")
	@ResponseBody
	public JSONArray categoryTree(String categoryCode) {
		try {
			List<ProductCategoryEntity> productCategoryList = productCategoryService.listProductCategory();
			JSONArray rows = new JSONArray();
			for (ProductCategoryEntity category : productCategoryList) {
				JSONObject json = new JSONObject();
				json.put("id", category.getId());
				json.put("pid", category.getParentCategoryId());
				json.put("name", category.getCategoryName());
				rows.add(json);
			}
			return rows;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new JSONArray();
	}

	
	/**
	 * 跳转商品类型跳转页面
	 * @return
	 */
	@RequestMapping("/toProductCategorySelector")
	public String toProductCategorySelector(){
		return "/coupon/product_category_selector";
	}
	
	/**
	 * 查询商品分类列表(for selector)
	 * @param request
	 * @return
	 */
	@RequestMapping("/listProductCategoryForSelector")
	@ResponseBody
	public List<ProductCategoryEntity> listProductCategoryForSelector(HttpServletRequest request) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("parentCategoryId", request.getParameter("id"));
		List<ProductCategoryEntity> productCategoryList = productCategoryService.listProductCategoryForSelector(param);
		if(productCategoryList != null && productCategoryList.size() > 0){
			for (ProductCategoryEntity category : productCategoryList) {
				if(StringUtil.isNotEmpty(category.getSubCategoryListStr())){
					category.setIsParent("true");
				}else{
					category.setIsParent("false");
				}
			}
		}
		return productCategoryList;
	}
	
	
	/**
	 * 跳转商品类别信息查询页面
	 * 
	 * @param ProductCategory
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-08-31 23:52:27
	 */
	@RequestMapping("/toListProductCategoryPage")
	public String toListProductCategoryPage(
			ProductCategoryEntity productCategory, HttpServletRequest request) {
		return "product/productCategory_list";
	}

	/**
	 * 跳转到分类关联设置页面
	 * 
	 * @param productCategory
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年10月10日 下午7:15:39
	 */
	@RequestMapping("/toProductCategoryRelationSettingsPage")
	public String toProductCategoryRelationSettingsPage(
			HttpServletRequest request) {
		request.setAttribute("productCategoryId",
				request.getParameter("productCategoryId"));
		return "product/productCategory_relation_settings";
	}

	/**
	 * 分页查询商品类别信息列表
	 * 
	 * @param productCategory
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-08-31 23:52:27
	 */
	@RequestMapping("/listProductCategoryPage")
	@ResponseBody
	public JSONGrid listProductCategoryPage(
			ProductCategoryEntity productCategory, HttpServletRequest request) {
		// int
		// pageNum=Integer.parseInt(request.getParameter("page").toString());
		// int
		// numPerPage=Integer.parseInt(request.getParameter("rows").toString());
		int pageNum = 1;
		int numPerPage = 10000;
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);

		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			paramMap.put("status", productCategory.getStatus());
			paramMap.put("isDelete", IS_DELETE.NORMAL.getId());
			paramMap.put("categoryName", productCategory.getCategoryName());
			PageBean pageBean = productCategoryService.listProductCategoryPage(
					pageParam, paramMap);
			List dataList = pageBean.getRecordList();
			return new JSONGrid(pageBean.getRecordList(),
					pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询商品类别信息失败", logger, e);
		}
		return new JSONGrid();
	}

	/**
	 * 跳转新增页面
	 * 
	 * @return string 跳转页面路径
	 * @author xu_cc
	 * @date 2017-08-31 23:52:27
	 */
	@RequestMapping("/toAddProductCategory")
	public String toAddProductCategory(HttpServletRequest request) {
		request.setAttribute("opFlag", "add");
		String parentCategoryId = request.getParameter("parentCategoryId");
		if (StringUtil.isNotEmpty(parentCategoryId)) {
			ProductCategoryEntity productCategory = productCategoryService
					.getProductCategoryById(Long.parseLong(parentCategoryId));
			request.setAttribute("parentCategoryId", productCategory.getId());
			request.setAttribute("parentCategoryName",
					productCategory.getCategoryName());
		} else {
			request.setAttribute("parentCategoryId", 0);
			request.setAttribute("parentCategoryName", "根节点");
		}
		return "product/productCategory_form";
	}

	/**
	 * 跳转编辑页面
	 * 
	 * @return string 跳转页面路径
	 * @author xu_cc
	 * @date 2017-08-31 23:52:27
	 */
	@RequestMapping("/toUpdateProductCategory")
	public String toUpdateProductCategory(HttpServletRequest request) {
		// 编辑操作
		request.setAttribute("opFlag", "edit");
		long id = Long.valueOf(request.getParameter("id"));
		try {
			// 获取分类列表
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("status", STATUS.ENABLED.getId());
			param.put("isDelete", IS_DELETE.NORMAL.getId());
			List<ProductCategoryEntity> productCategoryList = productCategoryService.listProductCategory(param);
			request.setAttribute("productCategoryList", productCategoryList);
			// 获取分类信息
			ProductCategoryEntity productCategory = productCategoryService.getProductCategoryById(id);
			request.setAttribute("productCategory", productCategory);
		} catch (Exception e) {
			handleException("跳转编辑商品类别信息页面错误", logger, e);
		}
		return "product/productCategory_form";
	}

	/**
	 * 新增或保存商品类别信息
	 * 
	 * @param request
	 *            请求对象
	 * @param productCategoryEntity
	 *            商品类别信息实体
	 * @return
	 * @author xu_cc
	 * @date 2017-08-31 23:52:27
	 */
	@RequestMapping("/saveOrUpdateProductCategory")
	@ResponseBody
	public Map<String, Object> saveProductCategory(HttpServletRequest request,
			ProductCategoryEntity productCategoryEntity) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		String msg = "";
		try {
			String id = request.getParameter("id");
			if (StringUtil.isNotEmpty(id)) {
				if (productCategoryEntity.getParentCategoryId() != null
						&& productCategoryEntity.getParentCategoryId() == Long.parseLong(id)) {
					result = 0;
					msg = "上级分类节点不能为当前节点！";
				} else {
					result = productCategoryService
							.updateProductCategory(productCategoryEntity);
					msg = "商品分类更新成功";
				}
			} else {
				productCategoryEntity.setStatus(1);
				productCategoryEntity.setCreater(this.getUserName());
				result = (int) productCategoryService.saveProductCategory(productCategoryEntity);
				msg = "商品分类新增成功";
			}
			if (result > 0) {
				result = 1;
			}
			resultMap.put("code", result);
			resultMap.put("msg", msg);
		} catch (Exception e) {
			msg = "添加/更新商品类别信息失败";
			resultMap.put("code", 0);
			resultMap.put("msg", msg);
			handleException(msg, logger, e);
		}
		return resultMap;
	}

	/**
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年9月14日 上午8:59:34
	 */
	@RequestMapping("/removeProductCategoryById")
	@ResponseBody
	public Map<String, Object> removeProductCategoryById(
			HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		String msg = "";
		try {
			String strId = request.getParameter("id");
			if (StringUtil.isNotEmpty(strId)) {
				Long id = Long.parseLong(strId);
				// 判断是否还有子分类
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("parentCategoryId", id);
				param.put("isDelete", IS_DELETE.NORMAL.getId());
				List<ProductCategoryEntity> productCategoryList = productCategoryService
						.listProductCategory(param);
				if (productCategoryList != null
						&& productCategoryList.size() > 0) {
					result = 0;
					msg = "此分类下面有子分类，禁止删除！";
				} else {
					result = productCategoryService
							.deleteProductCategoryById(id);
					msg = "商品分类删除成功!";
				}
			} else {
				result = 0;
				msg = "未获取到主键ID";
			}
			resultMap.put("code", result);
			resultMap.put("msg", msg);
		} catch (Exception e) {
			msg = "删除商品类别信息失败!";
			resultMap.put("code", 0);
			resultMap.put("msg", msg);
			handleException(msg, logger, e);
		}
		return resultMap;
	}

	/**
	 * 获取商品分类列表
	 * 
	 * @param request
	 * @return List<ProductCategoryEntity>
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年9月28日 下午3:47:45
	 */
	@RequestMapping("/getCategoryList")
	@ResponseBody
	public List<ProductCategoryEntity> getCategoryList(
			HttpServletRequest request, String parentCategoryId) {
		try {
			if (StringUtil.isEmpty(parentCategoryId)) {
				parentCategoryId = "0";
			}
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("parentCategoryId", parentCategoryId);
			param.put("isDelete", IS_DELETE.NORMAL.getId());
			return productCategoryService.listProductCategory(param);
		} catch (Exception e) {
			e.printStackTrace();
			return new ArrayList<ProductCategoryEntity>();
		}
	}
}
